package com.perfma.xtest.cmd;

import java.util.Map;

public class ScriptJobHandler extends IJobHandler {

    private Long jobId;
    private long glueUpdatetime;
    private String gluesource;
    private Map map;

    public ScriptJobHandler(Long jobId, long glueUpdatetime, String gluesource, Map map) {
        this.jobId = jobId;
        this.glueUpdatetime = glueUpdatetime;
        this.gluesource = gluesource;
        this.map = map;
    }

    public long getGlueUpdatetime() {
        return glueUpdatetime;
    }

    @Override
    public ReturnT<String> execute() throws Exception {

        // cmd + script-file-name
        String cmd = "bash";
        String scriptFileName = null;
        scriptFileName = ScriptUtil.GLUESOURCE_PATH.concat("/").concat(String.valueOf(jobId)).concat("_").concat(String.valueOf(glueUpdatetime)).concat(".sh");
        // make script file
        ScriptUtil.markScriptFile(scriptFileName, gluesource);

        // log file
        String logFileName = JobFileAppender.logPath.concat(JobFileAppender.contextHolder.get());

        // invoke
        JobLogger.log("----------- 脚本文件: " + scriptFileName + " -----------");
        int exitValue = ScriptUtil.execToFile(map, cmd, scriptFileName, logFileName, jobId);
        ReturnT<String> result = (exitValue == 0) ? ReturnT.SUCCESS : new ReturnT<String>(ReturnT.FAIL_CODE, "script exit value(" + exitValue + ") is failed");
        result.setGluesourcePath(scriptFileName);
        return result;
    }

}
